package com.larissa.android.quizdemo;

import android.util.Log;

import androidx.lifecycle.SavedStateHandle;
import androidx.lifecycle.ViewModel;

public class QuizViewModel extends ViewModel {
    private static final String TAG="QuizViewModel";
    private static final String CURRENT_INDEX="Current_index";
    private static final String CURRENT_COUNT="Current_count";
    private SavedStateHandle mSavedStateHandle;

//    int mCurrentIdx=0;
//    int mCount=0;

    int mCurrentIdx;
    int mCount;

    private boolean mCurrentQuestionAnswer;
    private int mCurrentQuestionText;

    public boolean isCurrentQuestionAnswer() {
        if(mCurrentIdx==-1){
            return mQuestions[mQuestions.length-1].isQuestionAnswer();
        }else
            return mQuestions[mCurrentIdx].isQuestionAnswer();
    }

    public int getCurrentQuestionText() {
        if(mCurrentIdx==-1)
            return mQuestions[mQuestions.length-1].getQuestionId();
        else
            return mQuestions[mCurrentIdx].getQuestionId();
    }

    private Question[] mQuestions=new Question[]{
            new Question(R.string.test_bj,true),
            new Question(R.string.test_dc,false),
            new Question(R.string.test_london,true),
            new Question(R.string.test_tokyo,true)
    };

    public QuizViewModel(SavedStateHandle savedStateHandle){
        Log.d(TAG,"ViewModel instance created");
        mSavedStateHandle=savedStateHandle;
        mCurrentIdx=mSavedStateHandle.get(CURRENT_INDEX)==null? 0: mSavedStateHandle.get(CURRENT_INDEX);
        Log.i(TAG,String.format("current index:%s",mCurrentIdx));
        mCount=mSavedStateHandle.get(CURRENT_COUNT)==null?0:mSavedStateHandle.get(CURRENT_COUNT);
        Log.i(TAG,String.format("current count:%s",mCount));
    }

//    boolean mCurrentQuestionAnswer=mQuestions[mCurrentIdx].isQuestionAnswer();
//    int mCurrentQuestionText=mQuestions[mCurrentIdx].getQuestionId();

    public void moveToNext(){
        mCurrentIdx++;
        if(mCurrentIdx>=mQuestions.length){
            mCurrentQuestionText=mQuestions[mCurrentIdx-1].getQuestionId();
            mCurrentIdx=-1;
        }else{
            mCurrentQuestionAnswer=mQuestions[mCurrentIdx].isQuestionAnswer();
            mCurrentQuestionText=mQuestions[mCurrentIdx].getQuestionId();
        }
        mSavedStateHandle.set(CURRENT_INDEX,mCurrentIdx);
        mSavedStateHandle.set(CURRENT_COUNT,mCount);
    }

//    public QuizViewModel(){
//        Log.d(TAG,"ViewModel instance created");
//    }
//
    @Override
    protected void onCleared(){
        super.onCleared();
        Log.d(TAG,"ViewModel instance about to be destroyed");
    }
}